<template>
	<view class="change-mobile">
		<view class="get-code">
			<input type="text" class="set-phone" v-model="mobile" placeholder='请输入新的手机号'>
			<view class="commit" @tap="sendCode">{{btnText}}</view>
		</view>
		<input type="text" class="set-code" v-model="code" placeholder='请输入验证码'>
		<view class="next" @tap="commitChange">确认号码</view>
	</view>
</template>

<script>
	import storage from '@/commen/utils/storage'
	import {
		sendMessage,
		verifyCode,
		changeMobile
	} from '@/commen/js/config'

	export default {
		data() {
			return {
				time: 60, // 时间
				btnText: '发送验证码', // 提示文字
				mobile: '', // 手机号
				code: '', // 手机验证码
				oldCode: '', // 旧手机验证码
				sendKey: true, // 请求key
				token: '', // token暂存
			};
		},
		onLoad(ops) {
			this.token = storage.get('token')
			this.oldCode = ops.oldCode
		},
		methods: {
			// 发送验证码
			async sendCode() {
				if (!this.sendKey) return
				this.sendKey = false
				const params = {
					token: this.token,
					type: 1,
					phone: this.mobile
				}
				const [err, res] = await sendMessage(params)
				if (!res) return
				const t = setInterval(() => {
					this.time--
					this.btnText = this.time + 's后发送'
					if (this.time == 0) {
						clearInterval(t)
						this.btnText = '发送验证码'
						this.time = 60
						this.sendKey = true
					}
				}, 1000)
			},
			// 校验验证码
			async verifyCode() {
				const params = {
					token: this.token,
					code: this.code,
					type: 1,
					phone: this.mobile
				}
				const [err, res] = await verifyCode(params)
				if (!res) return 
				return res
			},
			// 修改手机号
			async commitChange() {
				const key = await this.verifyCode()
				if (!key) return
				const params = {
					token: this.token,
					new_phone: this.mobile,
					new_code: this.code,
					old_code: this.oldCode || ''
				}
				const [err, res] = await changeMobile(params)
				if (!res) return
				this.$toast(res.msg)
				storage.set('phone_no', this.mobile, 'userinfo')
				uni.$emit('refreshPhone')
				uni.$emit('refreshUserInfo')
				setTimeout(() => {
					this.$close()
				}, 1500)
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/static/scss/config.scss';
	@import '@/static/scss/mixin.scss';

	.change-mobile {
		@include box-w(100%);
		padding: 46rpx 32rpx 0;

		.get-code {
			@include flex-row(space-between);
			border: 2rpx solid $bg-a;
			padding-left: 26rpx;

			input {
				@include box(486rpx, 100rpx);
			}

			.commit {
				@include box(220rpx, 100rpx, $bg-d);
				@include font-set($font-a, $color-c);
				@include flex-row();
				border-left: 2rpx solid $bg-a;
			}
		}

		.set-code {
			margin-top: 46rpx;
			@include box(100%, 100rpx);
			border: 2rpx solid $bg-a;
			padding-left: 26rpx;
		}

		.next {
			@include box(296rpx, 100rpx, $bg-a);
			border-radius: 10rpx;
			box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.3);
			@include flex-row();
			@include font-set($font-a, $color-a);
			margin: 80rpx auto 0;
		}

	}
</style>
